﻿#include "pch.h"
#include "CameraController.h"

#include "core/KeyCodes.h"
#include "core/log/LogSystem.h"
#include "function/InputSystem/AbstractInput.h"

namespace Engine
{
	CameraController::CameraController(const float aspectRatio)
		: camera(-aspectRatio * 1.0f, aspectRatio * 1.0f, aspectRatio * (-1.0f), 1.0f),
		  aspectRatio(aspectRatio)
	{
	}

	void CameraController::OnUpdate(const float deltaTime)
	{
		if (AbstractInput::IsKeyPressed(A))
		{
			cameraPosition.x -= cameraMoveSpeed * deltaTime;
		}
		else if (AbstractInput::IsKeyPressed(D))
		{
			cameraPosition.x += cameraMoveSpeed * deltaTime;
		}

		if (AbstractInput::IsKeyPressed(W))
		{
			cameraPosition.y += cameraMoveSpeed * deltaTime;
		}
		else if (AbstractInput::IsKeyPressed(S))
		{
			cameraPosition.y -= cameraMoveSpeed * deltaTime;
		}

		camera.SetPosition(cameraPosition);
		camera.SetRotation(cameraRotation);
	}

	void CameraController::OnEvent(Event& event)
	{
		EventDispatcher dispatcher(event);
		dispatcher.Dispatch<MouseScrolledEvent>(BIND_EVENT_FUNCTION(CameraController::OnMouseScrolled));
		dispatcher.Dispatch<WindowResizeEvent>(BIND_EVENT_FUNCTION(CameraController::OnWindowResized));
	}

	bool CameraController::OnMouseScrolled(const MouseScrolledEvent& event)
	{
		zoomLevel -= event.GetYOffset() * 0.125f;
		zoomLevel = std::max(zoomLevel, 0.25f);
		camera.SetProjectionMatrix(-aspectRatio * zoomLevel, aspectRatio * zoomLevel, aspectRatio * (-zoomLevel),
		                           zoomLevel);

		return false;
	}

	bool CameraController::OnWindowResized(const WindowResizeEvent& event)
	{
		aspectRatio = static_cast<float>(event.GetWidth()) / static_cast<float>(event.GetHeight());
		camera.SetProjectionMatrix(-aspectRatio * zoomLevel, aspectRatio * zoomLevel, aspectRatio * (-zoomLevel),
		                           zoomLevel);

		return false;
	}
}
